<?php

namespace app\api\controller;

use app\admin\model\Record;
use app\admin\model\Subject;
use app\admin\model\SubjectExamItem;
use app\admin\model\SubjectRecord;
use app\common\controller\Api;
use app\admin\model\Subject as SubjectModel;
use app\common\model\QUser as QUser;

/**
 * 首页接口.
 */
class Question extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    protected function _initialize()
    {
    parent::_initialize();

    //24小时内未测评自动失效
        (new \app\admin\model\SubjectRecord())->where('starttime','<',time()-86400)->where('status',1)->update(['status'=>3]);

    }

    /**
     * 题库详情
     * @return void
     */
    public function detail()
    {
        $id = $this->request->get('id');
        $info = (new SubjectModel())->where('id', $id)->find();
        $info['usermobile'] = $this->auth->mobile;
        $this->success('成功', $info);
    }

    /**
     * 题库题目列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function subject_exam()
    {
        $subject_id = $this->request->get('subject_id');
        $record_id = $this->request->get('record_id', 0);
        $counselor_id = $this->request->get('counselor_id', 0);
        $info = (new SubjectModel())->where('id', $subject_id)->find();
        if (empty($info)) {
            $this->error('参数异常', ['msg' => 'subject_id对应信息不存在']);
        }


        $list = (new \app\admin\model\SubjectExam())->where('subject_id', $subject_id)->order('weigh asc')->select()->toArray();

        $SubjectExamItemModel = new SubjectExamItem();
        foreach ($list as &$vv) {
            $vv['item'] = $SubjectExamItemModel->where('subject_exam_id', $vv['id'])->order('weigh asc')->select()->toArray();
            $vv['type'] = $info['stype'];
        }
        $subjectRecordModel = new \app\admin\model\SubjectRecord();
        if ($record_id) {
            $info=$subjectRecordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
            if (empty($info)){
                $info = $subjectRecordModel->where('id', $record_id)->where('user_id', 0)->find();
            }
            if (empty($info)) {
                $this->error('参数异常', ['msg' => 'record_id对应信息不存在']);
            }
            $subjectRecordModel->where('id', $record_id)->update([
//                'starttime' => time(),
                'user_id' => $this->auth->id,
                'usermobile' => $this->auth->mobile,
                'username' =>  $this->auth->nickname,
                'examtime' => time(),
            ]);

        } else {
            $record_id = $subjectRecordModel->insertGetId(
                [
                    'subject_id' => $subject_id,
                    'counselor_id' => $counselor_id,
                    'counselor' => (new \app\common\model\Quser())->where('id',$counselor_id)->value('nickname') ,
                    'user_id' => $this->auth->id,
                    'starttime' => time(),
                    'examtime' => time(),
                    'status' => 1,
                    'usermobile' => $this->auth->mobile,
                    'username' =>  $this->auth->nickname,
                    'subject_name' => $info['name'],
                ]
            );
        }
        $this->success('成功', ['list' => $list, 'record_id' => $record_id]);
    }

    /**
     * 题目选项
     * @return void
     */
    public function subject_exam_item()
    {
        $subject_exam_id = $this->request->get('subject_exam_id');
        $item = (new SubjectExamItem())->where('subject_exam_id', $subject_exam_id)->order('weigh asc')->select()->toArray();
        $this->success('成功', $item);
    }

    /**
     * 测评分类
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cate()
    {
        $cateModel = new \app\common\model\Category();
        $subjectRecordModel = new \app\admin\model\SubjectRecord();
        $list = $cateModel->field('id,name,type,flag')->order('weigh desc')->where('type', 'subject')->where('status', 'normal')->select()->toArray();
        $_list = [];
        if ($this->auth->id) {
            $count = $subjectRecordModel->where('user_id', $this->auth->id)->count();
            $count && $_list[] = [
                'id' => 99999,
                'name' => '我的常用'
            ];
        }
        foreach ($list as $vv) {
            $_list[] = [
                'id' => $vv['id'],
                'name' => $vv['name']
            ];
        }
        $this->success('请求成功', $_list);
    }

    /**
     * 题库列表
     * @return void
     */
    public function index()
    {

        $cate_id = $this->request->get('cate_id');
        $keywords = $this->request->get('keywords');
        //如果为我的常用
        if ($cate_id == 99999) {
            $subject_id = (new \app\admin\model\SubjectRecord())->group('subject_id')->where('user_id', $this->auth->id)->column('subject_id');
            $where['subject_id'] = $subject_id;
        } else {
            $where['category_id'] = $cate_id;
        }
        $where['keywords'] = $keywords;
        $model = new SubjectModel();
        $list = $model->getList($where, 12, 'id,name,source');
        foreach ($list['data'] as &$vv) {
            $vv['num'] = (new \app\admin\model\SubjectRecord())->where('subject_id', $vv['id'])->where('status', 2)->count();
        }
        $this->success('请求成功', $list);
    }

    /**
     * 测评记录
     * @return void
     */
    public function record()
    {
        $data = $this->request->get([
            'size' => 12,
            'keywords' => '',
            'status' => -1
        ]);
        $data['user_id'] = $this->auth->id;
        $with = ['userinfo' => function ($query) {
            $query->field('id,username,prevtime,logintime,jointime');
        }, 'quser' => function ($query) {
            $query->field('id,username');
        },
            'subject' => function ($query) {
                $query->field('id,name,subject_cate_id');
            }
        ];
        $list = (new SubjectRecord())->getuserList($data, $data['size'], '*', 'id desc', $with);

        foreach ($list['data'] as &$vv){
            !$vv['counselor'] && $vv['counselor'] = $vv['username'];
        }
        $this->success('成功', $list);
    }

    /**
     *提交答案
     * @return void
     */
    public function submit()
    {

        try {
            $counselor_id = $this->request->post('counselor_id');
            $record_id = $this->request->post('record_id');
            $subject_id = $this->request->post('subject_id');


            $data = $this->request->post('data', [], null);
            $data = json_decode($data, true);
            if (!$subject_id || empty($data)) {
                $this->error('参数异常', ['record_id' => $record_id, 'counselor_id' => $counselor_id, 'subject_id' => $subject_id, 'data' => $data]);
            }
            $sublectRecordModel = new SubjectRecord();
            $info = $sublectRecordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
            if (empty($info)) {
                $this->error('未找到测评记录');
            }

            $subject = (new Subject())->where('id',$subject_id)->find();
            if ($info['status'] != 1) {
                $this->error('测评记录异常');
            }
            $score = 0;
            $num = 0;
            $yang_num = $ying_num = 0;
            $yang_score = $ying_score = 0;
            foreach ($data as $vv) {
                $num++;
                //滑动选择分数
                if ($vv['questionType'] == 2) {
                    foreach ($vv['checkOptionlist'] as $v2) {
                        $score += $v2['silderOptionValue'];
                    }
                }
                //单选
                if ($vv['questionType'] == 1) {
                    $score += $vv['score'];
                    if ($vv['score'] > 0) {
                        $yang_num++;
                        $yang_score += $vv['score'];
                    } else {
                        $ying_num++;
                        $ying_score += $vv['score'];
                    }
                }
            }
            $report = [];

            $resultReportModel = new \app\admin\model\SubjectResult();
//        dump($data);
//            dump($score);die;
//            dump($subject);die;
            //生成报告 无因子
            if ($subject['subject_cate_id'] == 3) {

                $report = $resultReportModel->where('subject_id', $info['subject_id'])
                    ->where('min', "<=", $score)
                    ->where('max', ">", $score)
                    ->find();
                if (empty($report)) {
                    $this->error('系统配置异常');
                }
                $report = [
                    'score' =>$score,
                    'report_title' => $report['report_title'],
                    'report_content' => $report['report'],
                    'report_desc' => ''
                ];

            }
            //生成报告 多因子
            if ($subject['subject_cate_id'] == 1) {
                $allreport = $resultReportModel->where('subject_id', $info['subject_id'])
                    ->where('result_type', 1)
                    ->where('min', "<=", $score)
                    ->where('max', ">", $score)
                    ->find();
                if (empty($allreport)) {
                    $this->error('系统配置异常:总分'.$score);
                }
                $agv_score = round($score / $num, 2);
                $avgreport = $resultReportModel->where('subject_id', $info['subject_id'])
                    ->where('result_type', 2)
                    ->where('min', "<=", $agv_score)
                    ->where('max', ">", $agv_score)
                    ->find();
                if (empty($avgreport)) {
                    $this->error('系统配置异常:总均分'.$agv_score);
                }
                $yangreport = $resultReportModel->where('subject_id', $info['subject_id'])
                    ->where('result_type', 3)
                    ->where('min', "<=", $yang_num)
                    ->where('max', ">", $yang_num)
                    ->find();
                if (empty($yangreport)) {
                    $this->error('系统配置异常:阳性项目数');
                }
                $yingreport = $resultReportModel->where('subject_id', $info['subject_id'])
                    ->where('result_type', 4)
                    ->where('min', "<=", $ying_num)
                    ->where('max', ">", $ying_num)
                    ->find();
                if (empty($yingreport)) {
                    $this->error('系统配置异常:阴性项目数');
                }
                $agv_yang_score = round($yang_score / $yang_num, 1);
                $agvyangscorereport = $resultReportModel->where('subject_id', $info['subject_id'])
                    ->where('result_type', 5)
                    ->where('min', "<=", $agv_yang_score)
                    ->where('max', ">", $agv_yang_score)
                    ->find();
                if (empty($agvyangscorereport)) {
                    $this->error('系统配置异常:阳性症状均分');
                }
                //处理因子
                $factorconfigModel = new \app\admin\model\FactorConfig();
                $factorlist = [];
                foreach ($data as $vv) {
                    //题目关联的因子
                    $questioninfo = (new \app\admin\model\SubjectExam())->where('id', $vv['questionId'])->find();
                    if ($questioninfo['factor_id']){
                        $factorlist[] = [
                            'factor_id' => $questioninfo['factor_id'],
                            'score' => $vv['score'],
                            'subject_exam_item_id' => $vv['checkOptionId'],
                            'subject_exam_id' => $questioninfo['id'],
                            'type'=>'exam'
                        ];
                    }
                    //选项关联的因子  存在问题就是 选项和题目都关联同一个因子 那这个因子的分数会累加
                    $optioninfo = (new \app\admin\model\SubjectExamItem())->where('id', $vv['checkOptionId'])->find();
                    if ($optioninfo['factor_id']){
                    $factorlist[] = [
                        'factor_id' => $optioninfo['factor_id'],
                        'score' => $vv['score'],
                        'subject_exam_item_id' => $vv['checkOptionId'],
                        'subject_exam_id' => $optioninfo['subject_exam_id'],
                        'type'=>'item'
                    ];
                    }
                }
                //计算因子
                $factor_report = $factorconfigModel->cal($factorlist,['score'=>$score,'num'=>$num]);
                $report = [
                    'all' => [
                        ['title' => '总分', 'val' => $score, 'content' => $allreport['report'], 'desc' => $allreport['desc'], 'level' => $allreport['level']],
                        ['title' => '总均分', 'val' => $agv_score, 'content' => $avgreport['report'], 'desc' => $avgreport['desc'], 'level' => $avgreport['level']],
                        ['title' => '阳性项目数', 'val' => $yang_num, 'content' => $yangreport['report'], 'desc' => $yangreport['report'], 'level' => $yangreport['level']],
                        ['title' => '阴性项目数', 'val' => $ying_num, 'content' => $yingreport['report'], 'desc' => $yingreport['report'], 'level' => $yingreport['level']],
                        ['title' => '阳性症状均分', 'val' => $agv_yang_score, 'content' => $agvyangscorereport['report'], 'desc' => $agvyangscorereport['report'], 'level' => $agvyangscorereport['level']],
                    ],
                    'factor' => ['desc' => $subject['factor_desc'],
                        'item' => $factor_report
                    ],
                    'report_desc' => $subject['desc'],

                ];
            }
            //生成报告 滑动
            if ($subject['subject_cate_id'] == 5) {


//                throw new \Exception('调试');
                $report_score = [];
                $factorconfigModel = new \app\admin\model\FactorConfig();
                $factorlist = [];

                foreach ($data as $vv) {
                    //滑动选择分数

                    foreach ($vv['checkOptionlist'] as $v2) {
                        $optioninfo = (new \app\admin\model\SubjectExamItem())->where('id', $v2['silderOptionId'])->find();

                        $report_score[] = [
                            'title' => $optioninfo['name'],
                            'score' => $v2['silderOptionValue'],
                            'avg_score' => $v2['silderOptionValue'],
                            'item_id' => $v2['silderOptionId'],
                            'max' => $optioninfo['max'],
                        ];



                        //题目关联的因子
                        $questioninfo = (new \app\admin\model\SubjectExam())->where('id', $vv['questionId'])->find();
                        if ($questioninfo['factor_id']){
                            $factorlist[] = [
                                'factor_id' => $questioninfo['factor_id'],
                                'score' => $v2['silderOptionValue'],
                                'subject_exam_item_id' => $v2['silderOptionId'],
                                'subject_exam_id' => $questioninfo['id'],
                                'type'=>'exam'
                            ];
                        }

                        //选项关联的因子  存在问题就是 选项和题目都关联同一个因子 那这个因子的分数会累加
                        $optioninfo = (new \app\admin\model\SubjectExamItem())->where('id', $v2['silderOptionId'])->find();
                        if ($optioninfo['factor_id']){
                            $factorlist[] = [
                                'factor_id' => $optioninfo['factor_id'],
                                'score' => $v2['silderOptionValue'],
                                'subject_exam_item_id' => $v2['silderOptionId'],
                                'subject_exam_id' => $optioninfo['subject_exam_id'],
                                'type'=>'item'
                            ];
                        }
                    }
                }

                foreach ($report_score as &$vv){
                    $itemreport = $resultReportModel->where('subject_id', $info['subject_id'])
                        ->where('result_type', 7)
                        ->where('item_id', $vv['item_id'])
                        ->where('min', "<=", $vv['score'])
                        ->where('max', ">", $vv['score'])
                        ->find();
                    if (empty($itemreport)) {
                        $this->error('系统配置异常,item_id:'.$vv['item_id']);
                    }
                    $vv['content'] = $itemreport['report'];
                    $vv['desc'] = $itemreport['desc'];
                }


                //计算因子
                $factor_report = $factorconfigModel->cal($factorlist,['score'=>$score,'num'=>$num]);

                $report = [
                    'score' =>$report_score ,
                    'factor' => ['desc' => $info['factor_desc'],
                        'item' => $factor_report
                    ],

                    'report_title' => '',
                    'report_content' => '',
                    'report_desc' => ''
                ];

            }
//        dump($info);
//            dump($report);die;
            $result = $sublectRecordModel->where('id', $record_id)->update([
                'score' => $score,
                'endtime' => time(),
                'result' => json_encode($data, JSON_UNESCAPED_UNICODE),
                'report' => json_encode($report, JSON_UNESCAPED_UNICODE),
                'status' => 2,
                'usermobile' => $this->auth->mobile,
                'username' =>  $this->auth->nickname,
                'subject_name' => $subject['name'],
            ]);

            $this->success('成功');
        } catch (\Exception $e) {
            $this->error('系统异常：' . $e->getMessage());
        }
    }


    /**
     * 查看报告
     * @return void
     */
    public function report()
    {
        $record_id = $this->request->get('record_id');
        $sublectRecordModel = new SubjectRecord();
        $info = $sublectRecordModel->where('id', $record_id)->with([
            'subject' => function ($query) {
                $query->field('id,name,subject_cate_id');
            },
            'userinfo' => function ($query) {
                $query->field('id,nickname,prevtime,logintime,jointime,mobile');
            },
        ])->field('id,examtime,counselor_id,result,subject_id,user_id,score,report')->find();
        if (empty($info)) {
            $this->error('信息异常');
        }
        $info['qrcode'] = config('site.gongzhonghao');
        $info['link'] = config('site.gongzhonghao_link');
        $info['examtime'] = date('Y-m-d H:i:s',$info['examtime']);

        //1 SCL
        //2	多维度
        //3	单维度
        //4	MBTI
        //5	ORS / SRS

        switch ($info['subject']['subject_cate_id']) {
            case '1':
                $report = [
                    'all' => [
                        ['title' => '总分', 'val' => rand(100, 999), 'content' => '有比较严重的心理问题，需医学上的详细检查', 'desc' => '总体得分，能反映病情严重程度。', 'level' => 1],
                        ['title' => '总均分', 'val' => rand(1, 10), 'max' => 10, 'agv_score' => rand(1, 10), 'content' => '是指总的来者，被试的自我症状评价介于“没有"到“严重”的哪一个水平。', 'desc' => '是指总的来者，被试的自我症状评价介于“没有"到“严
重”的哪一个水平。', 'level' => 2],
                        ['title' => '阳性项目数', 'val' => rand(1, 10), 'max' => 10, 'agv_score' => rand(1, 10), 'content' => '阳性因子数较多，超出正常范国', 'desc' => '表示被试在多少项目中感到“有症状”', 'level' => 2],
                    ],
                    'factor' => ['desc' => '', 'item' => [
                        ['title' => '抑郁', 'score' => rand(10, 40), 'avg_score' => rand(10, 40) / 10, 'max' => 100, 'content' => '抑郁程度较强，生活缺乏足够的兴趣，缺乏运动活力，极端情况下，可能会有想死亡的思想和自杀的观念。', 'desc' => '该分星表的得分在0-52分之间。得分越高，抑郁程度越明显，得分越低，抑郁程度越不明显。
因子介绍:苦闷的情感与心境为代表性症状，还以生话兴迎的减退，动力缺乏，活力丧失等为特征。还表现出失望、悲观以与抑和相联系的认知和躯体方面的感受，另外，还包括有上元亡的思想和自杀观念。'],

                        ['title' => '敌对', 'score' => rand(10, 40), 'avg_score' => rand(10, 40) / 10, 'max' => 100, 'content' => '易表现出敌对的思想、情恶和行为。', 'desc' => '该分量表的得分在0-24分之间。得分越高，个体越客易敌对，好争论，脾气难以控制。得分越低，个体的脾气越温和。待人友好，不喜欢争论、无破坏行为。因子介绍:主要从三方面来反映敌对的表现:思想、感情及行为。其项目包括厌烦的感觉，捧物，争论直到不可控制的胂气县发等各方面。'],
                    ]],
                    'report_desc' => '《SCL-90心理健康症状自评量表》包含了广泛的精神病症状学内容，如思维、情感、人际关系和生活习惯等。
该量表从9个方面，以身心症状表现的角度考查了受测者的心理健康水平，如果在某些症状上的得分越高，感觉到某些症状的频度和强度都比较严重，就应该注意受测者在这个方面的问题。
由于自评量表是测量受测者在一段时间内感觉到的症状的严重与否，所以在量表分数的解释上应该慎重，并不是得分高就一定说明出现了很严重的心理问题，某些分量表上的得分较高有可能只是由于受测者当时遇到了一些难题如失恋、面临考试、生病等，因此还应该对得分高的原因作进一步的了解。
如果受测者在多个维度上自觉这些症状较为严重时，应该加强心理健康的教育，严重时应该到比较权威的心理咨询和治疗机构进行进一步的检查和诊断。',

                ];

                break;
            case '3':
                $report = [
                    'score' => $info['score'],
                    'report_title' => '轻度抑郁症',
                    'report_content' => '测试结果显示出，你目前可能有轻微的情绪波动或轻微的焦虑情绪，比如偶尔会有莫名的紧张，难以放松，对未来的担忧等，这些尚在你可以应付的范里
                                        内.量表只起到初步判断，如果判断自己是不是抑郁，一定要到专业精神科，医生通过全面精神状态检查判断是不是抑郁症。',
                    'report_desc' => '参考标准:
                                    ·0-5分属于健康程度
                                    10-15分属于轻度抑郁的症状
                                    >15分称为有抑郁的症状
                                    >25分称为严重或重度的抑郁症状'
                ];
                break;
            case '5':
                $report = [
                    'score' => [['title' => '身心健康', 'score' => 35, 'avg_score' => 100, 'max' => 100, 'content' => '身心健康:35'], ['title' => '人际关系', 'score' => 10, 'avg_score' => 100, 'max' => 100, 'content' => '身心健康:35'], ['title' => '生活社交', 'score' => 45, 'avg_score' => 100, 'max' => 100, 'content' => '身心健康:35'], ['title' => '整体情况', 'score' => 45, 'avg_score' => 100, 'max' => 100, 'content' => '身心健康:35']],
                    'report_title' => '',
                    'report_content' => '',
                    'report_desc' => ''
                ];

                break;

        }


//        dump($info['report']);die;
        $info['report'] = json_decode($info['report'],true);
        $this->success('成功', $info);

    }

    /**
     * 上传图片
     * @return void
     */
    public function chart(){

        $record_id = $this->request->post('record_id');
        $image = $this->request->post('image');
        $result = $this->base64($image,$record_id);
        if($result===false){
            $this->error('失败');
        }
        (new SubjectRecord())->where('id',$record_id)->where('user_id',$this->auth->id)->update(['chartimg'=>$result]);
        $this->success('成功', ['url'=>$this->request->domain().$result]);
    }


    public function base64($image,$record_id){


      $imageName = "pdfimage_".$record_id.'.png';
        if (strstr($image,",")){
            $image = explode(',',$image);
            $image = $image[1];
        }

        $path = public_path()."uploads/".date("Ymd",time());
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建
            mkdir($path,0777,true);
        }
        $imageSrc=  $path."/". $imageName;  //图片名字


//        dump($imageSrc);
        $r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
        if (!$r) {
          return false;
        }else{
           return "/uploads/".date("Ymd",time()).'/'.$imageName;
        }

    }


}
